<template>
  <div class="approval-history">
    <div class="history-header" v-if="showHeader">
      <h3 class="history-title">
        <span class="title-icon">📜</span>
        审批历史
      </h3>
      <div class="history-summary">
        <div class="summary-item">
          <span class="summary-label">总记录</span>
          <span class="summary-value">{{ total }}</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">通过率</span>
          <span class="summary-value success">{{ approvalRate }}%</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">平均用时</span>
          <span class="summary-value">{{ averageTime }}</span>
        </div>
      </div>
    </div>

    <!-- 筛选器 -->
    <div class="history-filters" v-if="showFilters">
      <el-form :model="filters" inline size="small">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item label="审批决定">
          <el-select v-model="filters.decision" placeholder="全部" clearable style="width: 120px">
            <el-option label="同意" value="通过" />
                          <el-option label="拒绝" value="驳回" />
            <el-option label="撤回" value="withdraw" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单类型">
          <el-select v-model="filters.orderType" placeholder="全部" clearable style="width: 120px">
            <el-option label="标准采购" value="标准采购" />
            <el-option label="紧急采购" value="紧急采购" />
            <el-option label="框架采购" value="框架采购" />
            <el-option label="补充采购" value="补充采购" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 历史记录列表 -->
    <div class="history-content" v-loading="loading">
      <div v-if="!records.length" class="empty-state">
        <el-empty description="暂无审批历史记录" />
      </div>

      <div v-else class="history-list">
        <!-- 列表视图 -->
        <div v-if="viewMode === 'list'" class="list-view">
          <div 
            v-for="record in records" 
            :key="record.id"
            class="history-item"
            @click="handleRecordClick(record)"
          >
            <div class="item-header">
              <div class="order-info">
                <span class="order-number">{{ record.orderNumber }}</span>
                <el-tag :type="getOrderTypeTagType(record.orderType)" size="small">
                  {{ record.orderType }}
                </el-tag>
              </div>
              <div class="decision-info">
                <el-tag :type="getDecisionTagType(record.decision)" class="decision-tag">
                  <el-icon class="decision-icon">
                    <component :is="getDecisionIcon(record.decision)" />
                  </el-icon>
                  {{ getDecisionText(record.decision) }}
                </el-tag>
              </div>
            </div>

            <div class="item-content">
              <div class="content-left">
                <div class="supplier">供应商：{{ record.supplierName }}</div>
                <div class="amount">金额：¥{{ formatCurrency(record.orderAmount) }}</div>
                <div class="time">审批时间：{{ formatDateTime(record.approvalTime) }}</div>
              </div>
              <div class="content-right">
                <div class="duration">
                  <el-icon><Clock /></el-icon>
                  {{ record.processingDurationMinutes }}分钟
                </div>
                <div v-if="record.approvalComments" class="comments-preview">
                  {{ truncateText(record.approvalComments, 50) }}
                </div>
              </div>
            </div>

            <div class="item-footer" v-if="record.statusAfter">
              <div class="status-change">
                状态变更：{{ record.statusBefore }} → {{ record.statusAfter }}
              </div>
            </div>
          </div>
        </div>

        <!-- 表格视图 -->
        <div v-else class="table-view">
          <el-table :data="records" stripe border>
            <el-table-column prop="orderNumber" label="订单号" width="160">
              <template #default="{ row }">
                <el-link type="primary" @click="handleRecordClick(row)">
                  {{ row.orderNumber }}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column prop="supplierName" label="供应商" width="200" show-overflow-tooltip />
            <el-table-column prop="orderType" label="订单类型" width="120">
              <template #default="{ row }">
                <el-tag :type="getOrderTypeTagType(row.orderType)" size="small">
                  {{ row.orderType }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="orderAmount" label="订单金额" width="120" align="right">
              <template #default="{ row }">
                ¥{{ formatCurrency(row.orderAmount) }}
              </template>
            </el-table-column>
            <el-table-column prop="decision" label="审批决定" width="120">
              <template #default="{ row }">
                <el-tag :type="getDecisionTagType(row.decision)">
                  {{ getDecisionText(row.decision) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="processingDurationMinutes" label="处理用时" width="100" align="center">
              <template #default="{ row }">
                {{ row.processingDurationMinutes }}分钟
              </template>
            </el-table-column>
            <el-table-column prop="approvalTime" label="审批时间" width="160">
              <template #default="{ row }">
                {{ formatDateTime(row.approvalTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="approvalComments" label="审批意见" min-width="200" show-overflow-tooltip />
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="showPagination">
          <el-pagination
            v-model:current-page="pagination.pageIndex"
            v-model:page-size="pagination.pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 统计图表 -->
    <div class="history-charts" v-if="showCharts">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="chart-container">
            <h4 class="chart-title">审批决定分布</h4>
            <div class="decision-stats">
              <div 
                v-for="stat in decisionStats" 
                :key="stat.decision"
                class="stat-item"
              >
                <div class="stat-header">
                  <el-tag :type="getDecisionTagType(stat.decision)" size="small">
                    {{ getDecisionText(stat.decision) }}
                  </el-tag>
                  <span class="stat-count">{{ stat.count }}</span>
                </div>
                <div class="stat-bar">
                  <div 
                    class="stat-progress"
                    :style="{ width: `${stat.percentage}%`, backgroundColor: getDecisionColor(stat.decision) }"
                  ></div>
                </div>
                <div class="stat-percentage">{{ stat.percentage.toFixed(1) }}%</div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="chart-container">
            <h4 class="chart-title">处理时长分布</h4>
            <div class="time-stats">
              <div 
                v-for="range in timeRangeStats" 
                :key="range.range"
                class="time-stat-item"
              >
                <span class="time-label">{{ range.range }}</span>
                <div class="time-bar">
                  <div 
                    class="time-progress"
                    :style="{ width: `${range.percentage}%` }"
                  ></div>
                </div>
                <span class="time-count">{{ range.count }}次</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="审批记录详情"
      width="600px"
      @close="closeDetailDialog"
    >
      <div v-if="detailDialog.record" class="record-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">
            {{ detailDialog.record.orderNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="供应商">
            {{ detailDialog.record.supplierName }}
          </el-descriptions-item>
          <el-descriptions-item label="订单类型">
            <el-tag :type="getOrderTypeTagType(detailDialog.record.orderType)">
              {{ detailDialog.record.orderType }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">
            ¥{{ formatCurrency(detailDialog.record.orderAmount) }}
          </el-descriptions-item>
          <el-descriptions-item label="审批决定">
            <el-tag :type="getDecisionTagType(detailDialog.record.decision)">
              {{ getDecisionText(detailDialog.record.decision) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处理用时">
            {{ detailDialog.record.processingDurationMinutes }}分钟
          </el-descriptions-item>
          <el-descriptions-item label="审批时间">
            {{ formatDateTime(detailDialog.record.approvalTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="状态变更">
            {{ detailDialog.record.statusBefore }} → {{ detailDialog.record.statusAfter }}
          </el-descriptions-item>
          <el-descriptions-item label="审批意见" :span="2">
            {{ detailDialog.record.approvalComments || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="closeDetailDialog">关闭</el-button>
        <el-button type="primary" @click="viewOrderDetail">查看订单</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { 
  Clock, 
  Check, 
  Close, 
  Upload, 
  RefreshRight 
} from '@element-plus/icons-vue'
import type { PurchaseOrderApprovalRecordDto } from '@/types/console'

// Props
interface Props {
  records?: PurchaseOrderApprovalRecordDto[]
  loading?: boolean
  showHeader?: boolean
  showFilters?: boolean
  showPagination?: boolean
  showCharts?: boolean
  viewMode?: 'list' | 'table'
  approver?: string
}

const props = withDefaults(defineProps<Props>(), {
  records: () => [],
  loading: false,
  showHeader: true,
  showFilters: true,
  showPagination: true,
  showCharts: true,
  viewMode: 'list'
})

// Emits
const emit = defineEmits<{
  'record-click': [record: PurchaseOrderApprovalRecordDto]
  'search': [filters: any]
  'page-change': [page: number, size: number]
  'view-order': [orderId: number]
}>()

// 响应式数据
const dateRange = ref<[string, string]>(['', ''])
const filters = reactive({
  decision: '',
  orderType: '',
  startDate: '',
  endDate: ''
})

const pagination = reactive({
  pageIndex: 1,
  pageSize: 20
})

const detailDialog = reactive({
  visible: false,
  record: null as PurchaseOrderApprovalRecordDto | null
})

// 计算属性
const total = computed(() => props.records.length)

const approvalRate = computed(() => {
  if (!props.records.length) return 0
  const approvedCount = props.records.filter(r => r.decision === '通过').length
  return Math.round((approvedCount / props.records.length) * 100)
})

const averageTime = computed(() => {
  if (!props.records.length) return '0分钟'
  const totalTime = props.records.reduce((sum, record) => 
    sum + (record.processingDurationMinutes || 0), 0
  )
  const avgTime = Math.round(totalTime / props.records.length)
  return `${avgTime}分钟`
})

const decisionStats = computed(() => {
  const stats = props.records.reduce((acc, record) => {
    const decision = record.decision
    if (!acc[decision]) {
      acc[decision] = 0
    }
    acc[decision]++
    return acc
  }, {} as Record<string, number>)

  return Object.entries(stats).map(([decision, count]) => ({
    decision,
    count,
    percentage: (count / props.records.length) * 100
  }))
})

const timeRangeStats = computed(() => {
  const ranges = [
    { range: '≤5分钟', min: 0, max: 5 },
    { range: '6-15分钟', min: 6, max: 15 },
    { range: '16-30分钟', min: 16, max: 30 },
    { range: '31-60分钟', min: 31, max: 60 },
    { range: '>60分钟', min: 61, max: Infinity }
  ]

  return ranges.map(range => {
    const count = props.records.filter(record => {
      const time = record.processingDurationMinutes || 0
      return time >= range.min && time <= range.max
    }).length
    
    return {
      ...range,
      count,
      percentage: props.records.length > 0 ? (count / props.records.length) * 100 : 0
    }
  })
})

// 方法
const handleDateRangeChange = (dates: [string, string] | null) => {
  if (dates) {
    filters.startDate = dates[0]
    filters.endDate = dates[1]
  } else {
    filters.startDate = ''
    filters.endDate = ''
  }
  handleSearch()
}

const handleSearch = () => {
  emit('search', { ...filters })
}

const resetFilters = () => {
  Object.assign(filters, {
    decision: '',
    orderType: '',
    startDate: '',
    endDate: ''
  })
  dateRange.value = ['', '']
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  emit('page-change', pagination.pageIndex, pagination.pageSize)
}

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  emit('page-change', pagination.pageIndex, pagination.pageSize)
}

const handleRecordClick = (record: PurchaseOrderApprovalRecordDto) => {
  detailDialog.visible = true
  detailDialog.record = record
  emit('record-click', record)
}

const closeDetailDialog = () => {
  detailDialog.visible = false
  detailDialog.record = null
}

const viewOrderDetail = () => {
  if (detailDialog.record) {
    emit('view-order', detailDialog.record.purchaseOrderId)
    closeDetailDialog()
  }
}

// 工具方法
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

const formatCurrency = (amount: number | undefined) => {
  if (!amount) return '0.00'
  return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

const truncateText = (text: string, maxLength: number) => {
  if (!text) return ''
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}

// 样式方法
const getDecisionTagType = (decision: string) => {
  const typeMap: Record<string, string> = {
    '通过': 'success',
    '驳回': 'danger',
    'withdraw': 'warning',
    'submit': 'primary'
  }
  return typeMap[decision] || 'primary'
}

const getDecisionText = (decision: string) => {
  const textMap: Record<string, string> = {
    '通过': '同意',
    '驳回': '拒绝',
    'withdraw': '撤回',
    'submit': '提交'
  }
  return textMap[decision] || decision
}

const getDecisionIcon = (decision: string) => {
  const iconMap: Record<string, any> = {
    '通过': Check,
    '驳回': Close,
    'withdraw': RefreshRight,
    'submit': Upload
  }
  return iconMap[decision] || Upload
}

const getDecisionColor = (decision: string) => {
  const colorMap: Record<string, string> = {
    '通过': '#67c23a',
    '驳回': '#f56c6c',
    'withdraw': '#e6a23c',
    'submit': '#409eff'
  }
  return colorMap[decision] || '#409eff'
}

const getOrderTypeTagType = (orderType: string | undefined) => {
  if (!orderType) return ''
  const typeMap: Record<string, string> = {
    '标准采购': '',
    '紧急采购': 'danger',
    '框架采购': 'success',
    '补充采购': 'warning'
  }
  return typeMap[orderType] || ''
}
</script>

<style scoped>
.approval-history {
  width: 100%;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #ebeef5;
}

.history-title {
  margin: 0;
  font-size: 1.2rem;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.title-icon {
  font-size: 1.3rem;
}

.history-summary {
  display: flex;
  gap: 2rem;
}

.summary-item {
  text-align: center;
}

.summary-label {
  display: block;
  font-size: 0.75rem;
  color: #666;
  margin-bottom: 0.25rem;
}

.summary-value {
  display: block;
  font-size: 1.25rem;
  font-weight: 600;
  color: #2c3e50;
}

.summary-value.success {
  color: #67c23a;
}

.history-filters {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 1rem;
}

.history-content {
  position: relative;
}

.empty-state {
  text-align: center;
  padding: 2rem;
}

.history-list {
  width: 100%;
}

.list-view {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.history-item {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 1rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.history-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.75rem;
}

.order-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.order-number {
  font-weight: 600;
  color: #303133;
}

.decision-tag {
  font-weight: 600;
}

.decision-icon {
  margin-right: 0.25rem;
}

.item-content {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.5rem;
}

.content-left {
  flex: 1;
}

.content-left > div {
  margin-bottom: 0.25rem;
  font-size: 0.875rem;
  color: #606266;
}

.content-right {
  text-align: right;
  min-width: 150px;
}

.duration {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 0.25rem;
  color: #67c23a;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.comments-preview {
  font-size: 0.8rem;
  color: #909399;
  font-style: italic;
}

.item-footer {
  padding-top: 0.5rem;
  border-top: 1px solid #f0f0f0;
  font-size: 0.8rem;
  color: #909399;
}

.table-view {
  margin-bottom: 1rem;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 1rem;
}

.history-charts {
  margin-top: 2rem;
  padding-top: 1.5rem;
  border-top: 1px solid #ebeef5;
}

.chart-container {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 1rem;
}

.chart-title {
  margin: 0 0 1rem 0;
  font-size: 1rem;
  font-weight: 600;
  color: #303133;
}

.decision-stats {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.stat-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  min-width: 100px;
}

.stat-count {
  font-weight: 600;
  color: #303133;
}

.stat-bar {
  flex: 1;
  height: 8px;
  background: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.stat-progress {
  height: 100%;
  transition: width 0.3s ease;
}

.stat-percentage {
  min-width: 50px;
  text-align: right;
  font-size: 0.875rem;
  color: #606266;
}

.time-stats {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.time-stat-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.time-label {
  min-width: 80px;
  font-size: 0.875rem;
  color: #606266;
}

.time-bar {
  flex: 1;
  height: 6px;
  background: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
}

.time-progress {
  height: 100%;
  background: #409eff;
  transition: width 0.3s ease;
}

.time-count {
  min-width: 50px;
  text-align: right;
  font-size: 0.875rem;
  color: #606266;
}

.record-detail {
  padding: 1rem 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .history-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }

  .history-summary {
    width: 100%;
    justify-content: space-around;
  }

  .item-header {
    flex-direction: column;
    gap: 0.5rem;
    align-items: flex-start;
  }

  .item-content {
    flex-direction: column;
    gap: 0.5rem;
  }

  .content-right {
    text-align: left;
  }

  .stat-item {
    flex-direction: column;
    align-items: stretch;
    gap: 0.5rem;
  }

  .stat-header {
    justify-content: space-between;
  }

  .time-stat-item {
    flex-direction: column;
    align-items: stretch;
    gap: 0.25rem;
  }

  .time-label,
  .time-count {
    text-align: left;
  }
}
</style> 